package com.celebracion.util;

import java.util.ArrayList;
import java.util.List;

import com.celebracion.R;
import com.celebracion.model.EventoModel;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;

public class DBUtil extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;
    private Context context;
	
	
    private static final String DB_CREATE = "Create table "+ EventoModel.TABLE_NAME +
                " ( " + EventoModel.COLUMN_NAME_NOMBRE_EVENTO+ " TEXT, "
                + EventoModel.COLUMN_NAME_DIRECCION+" TEXT, " 
                + EventoModel.COLUMN_NAME_ESTADO + " INTEGER, "
                + EventoModel._ID+ " INTEGER PRIMARY KEY AUTOINCREMENT);";
    
    private static DBUtil dbUtil=null;
    
    public static DBUtil getInstance(Context context){
    	if(dbUtil==null)
    		dbUtil=new DBUtil(context);
    	return dbUtil;
   		
    }
	private DBUtil(Context context) {
		super(context, "basedatos", null, DATABASE_VERSION);
		this.context=context;
		
		
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		  db.execSQL(DB_CREATE);

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}
	
	public void insert(String nombre, String direccion){
		SQLiteDatabase dbWritable = getWritableDatabase();

		// Create a new map of values, where column names are the keys
		ContentValues values = new ContentValues();
		values.put(EventoModel.COLUMN_NAME_DIRECCION, direccion);
		values.put(EventoModel.COLUMN_NAME_NOMBRE_EVENTO, nombre);
		values.put(EventoModel.COLUMN_NAME_ESTADO, 0);
		

		// Insert the new row, returning the primary key value of the new row
		long newRowId;
		newRowId = dbWritable.insert(
		         EventoModel.TABLE_NAME,
		         null,
		         values);
	}

	private Cursor getCursorEventos(String selection){
		SQLiteDatabase db = getReadableDatabase();
		
		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String[] projection= {EventoModel._ID,
								EventoModel.COLUMN_NAME_NOMBRE_EVENTO,
								EventoModel.COLUMN_NAME_DIRECCION ,
								EventoModel.COLUMN_NAME_ESTADO};
        
        String[] selectionArgs= {};
		// How you want the results sorted in the resulting Cursor
		String sortOrder = EventoModel._ID+ " DESC";

		Cursor c = db.query(
		    EventoModel.TABLE_NAME,  // The table to query
		    projection,                               // The columns to return
		    selection,                                // The columns for the WHERE clause
		    selectionArgs,                            // The values for the WHERE clause
		    null,                                     // don't group the rows
		    null,                                     // don't filter by row groups
		    sortOrder                                 // The sort order
		    );
		
		return c;
	}
	
	public int getCountEventos(){
		return getCursorEventos(null).getCount();
	}
	
	public List<EventoModel> getEventosNoActivos(){
		return getEventos("estado=0");
	}
	
	public EventoModel getEventoActivo(){
		List<EventoModel> evts=getEventos("estado=1");
		if(evts.size()>0)
			return evts.get(0);
		else
			return new EventoModel(-1,"eventoPreview","eventoPreview",0);
	}
	
	public boolean activarEvento(long idEvento){
		SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.ficheroPreferencias), Context.MODE_PRIVATE);
		int nActivaciones = sharedPref.getInt(context.getString(R.string.nActivacionesPreferencias), 0);
		if(nActivaciones>0){ 
			actualizarEstadoEvento(idEvento, 1);
			//Decrementamos el numero de activaciones
			nActivaciones--;
			Editor edit=sharedPref.edit();
     	   edit.putInt(context.getString(R.string.nActivacionesPreferencias), nActivaciones);
     	   edit.commit();
			return true;
					
		}else
			return false;
		
	}
	
	public List<EventoModel> getEventosFinalizados(){
		return getEventos("estado=2");
	}
	
	public void finalizarEvento(){
		actualizarEstadoEvento(getEventoActivo().getId(), 2);
	}
	
	private List<EventoModel> getEventos(String where){
		Cursor c=getCursorEventos(where);
		c.moveToFirst();
		List<EventoModel> result= new ArrayList<EventoModel>();
		EventoModel aux;
		if(c.getCount()>0)
			do{
				aux=new EventoModel(c.getLong(c.getColumnIndex(EventoModel._ID)),
						c.getString(c.getColumnIndex(EventoModel.COLUMN_NAME_NOMBRE_EVENTO)),
						c.getString(c.getColumnIndex(EventoModel.COLUMN_NAME_DIRECCION)),
						c.getLong(c.getColumnIndex(EventoModel.COLUMN_NAME_ESTADO))
						);
				result.add(aux);
			}while(c.moveToNext());
		return result;
	}
	
	public void deleteEvento(long id){
		SQLiteDatabase db = getWritableDatabase();

		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String selection=EventoModel._ID+"=?";
        String[] selectionArgs= {""+id};
		db.delete(
		    EventoModel.TABLE_NAME,  // The table to query
	    selection,                                // The columns for the WHERE clause
		    selectionArgs                            // The values for the WHERE clause
		    
		    );
		
	}
	
	private void actualizarEstadoEvento(long idEvento, long estado){
		SQLiteDatabase db = getReadableDatabase();

		// New value for one column
		ContentValues values = new ContentValues();
		values.put(EventoModel.COLUMN_NAME_ESTADO, estado);

		// Which row to update, based on the ID
		String selection = EventoModel._ID +" = ?";
		String[] selectionArgs = { String.valueOf(idEvento) };

		 db.update(
			EventoModel.TABLE_NAME,
		    values,
		    selection,
		    selectionArgs);
	}
	

	
	
}
